//
//  2. 两数相加.swift
//  LeetCodeTrain
//
//  Created by rjb on 2021/5/7.
//  Copyright © 2021 rjb. All rights reserved.
//

import Foundation
class Solution2 {
    func addTwoNumbers2(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
        let vHead = ListNode(-1)
        var p:ListNode? = vHead
        var p1 = l1
        var p2 = l2
        var flag = 0
        while p1 != nil || p2 != nil {
            var sum = 0
            if p1 != nil {
                sum += p1!.val
            }
            if p2 != nil {
                sum += p2!.val
            }
            sum += flag
            
            flag = sum / 10
            let val = sum % 10
            
            let node = ListNode(val)
            p?.next = node
            p = p?.next
            
            p1 = p1?.next
            p2 = p2?.next
        }
        if flag == 1{
            let node = ListNode(1)
            p?.next = node
        }
        return vHead.next
    }
    
    static func test() {
        let head1 = createNode()
        let head2 = createNode2()
        let solution = Solution2()
        let head3 = solution.addTwoNumbers2(head1, head2)
        print(head3)
    }
    static func createNode() -> ListNode?{
        let array = [2,4,3]
        var head: ListNode?
        var p: ListNode?
        for item in array {
            if head == nil {
                head = ListNode(item)
                p = head
            } else {
                let cur = ListNode(item)
                p?.next = cur
                p = cur
            }
        }
        return head
    }
    static func createNode2() -> ListNode?{
        let array = [5,6,4]
        var head: ListNode?
        var p: ListNode?
        for item in array {
            if head == nil {
                head = ListNode(item)
                p = head
            } else {
                let cur = ListNode(item)
                p?.next = cur
                p = cur
            }
        }
        return head
    }
}
